package com.example.examsystem.controller;

import com.example.examsystem.dto.ExamResultDto;
import com.example.examsystem.dto.PageResponse;
import com.example.examsystem.service.ExamResultService;
import com.example.examsystem.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 考试成绩控制器
 * 处理成绩的CRUD操作
 */
@RestController
@RequestMapping("/exam-results")
@RequiredArgsConstructor
@Slf4j
public class ExamResultController {
    
    private final ExamResultService examResultService;
    
    /**
     * 获取考试成绩列表
     * @param page 页码
     * @param size 每页大小
     * @param examId 考试ID
     * @param userId 用户ID
     * @param username 用户名
     * @param grade 等级
     * @param passStatus 通过状态
     * @param published 发布状态
     * @return 分页成绩列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('exam_result:view')")
    public ResponseEntity<PageResponse<ExamResultDto>> getExamResults(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long examId,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) Boolean passStatus,
            @RequestParam(required = false) Boolean published) {
        log.info("查询考试成绩列表 - 页码: {}, 大小: {}, 考试ID: {}, 用户ID: {}, 用户名: {}, 等级: {}, 通过状态: {}, 发布状态: {}", 
                page, size, examId, userId, username, grade, passStatus, published);
        PageResponse<ExamResultDto> results = examResultService.getExamResults(
            page, size, examId, userId, username, grade, passStatus, published);
        return ResponseEntity.ok(results);
    }
    
    /**
     * 获取考试成绩详情
     * @param id 成绩ID
     * @return 成绩详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('exam_result:view')")
    public ResponseEntity<ExamResultDto> getExamResult(@PathVariable Long id) {
        log.info("获取考试成绩详情 - ID: {}", id);
        ExamResultDto result = examResultService.getExamResult(id);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 根据考试记录ID获取成绩
     * @param examRecordId 考试记录ID
     * @return 考试成绩
     */
    @GetMapping("/by-record/{examRecordId}")
    @PreAuthorize("hasAuthority('exam_result:view')")
    public ResponseEntity<ExamResultDto> getResultByRecordId(@PathVariable Long examRecordId) {
        log.info("根据考试记录ID获取成绩 - 记录ID: {}", examRecordId);
        ExamResultDto result = examResultService.getResultByRecordId(examRecordId);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 生成考试成绩
     * @param examRecordId 考试记录ID
     * @return 生成的成绩
     */
    @PostMapping("/generate/{examRecordId}")
    @PreAuthorize("hasAuthority('exam_result:create')")
    public ResponseEntity<ExamResultDto> generateResult(@PathVariable Long examRecordId) {
        log.info("生成考试成绩 - 记录ID: {}", examRecordId);
        ExamResultDto result = examResultService.generateResult(examRecordId);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 更新成绩反馈
     * @param id 成绩ID
     * @param request 请求体
     * @return 更新的成绩
     */
    @PutMapping("/{id}/feedback")
    @PreAuthorize("hasAuthority('exam_result:update')")
    public ResponseEntity<ExamResultDto> updateFeedback(@PathVariable Long id, 
                                                       @RequestBody Map<String, String> request) {
        log.info("更新成绩反馈 - ID: {}", id);
        String feedback = request.get("feedback");
        ExamResultDto result = examResultService.updateFeedback(id, feedback);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 发布成绩
     * @param id 成绩ID
     * @return 发布的成绩
     */
    @PostMapping("/{id}/publish")
    @PreAuthorize("hasAuthority('exam_result:publish')")
    public ResponseEntity<ExamResultDto> publishResult(@PathVariable Long id) {
        log.info("发布成绩 - ID: {}", id);
        Long publisherId = SecurityUtils.getCurrentUserId();
        ExamResultDto result = examResultService.publishResult(id, publisherId);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 批量发布成绩
     * @param examId 考试ID
     * @return 发布数量
     */
    @PostMapping("/batch-publish/{examId}")
    @PreAuthorize("hasAuthority('exam_result:publish')")
    public ResponseEntity<Map<String, Integer>> batchPublishResults(@PathVariable Long examId) {
        log.info("批量发布成绩 - 考试ID: {}", examId);
        Long publisherId = SecurityUtils.getCurrentUserId();
        int count = examResultService.batchPublishResults(examId, publisherId);
        return ResponseEntity.ok(Map.of("publishedCount", count));
    }
    
    /**
     * 获取用户的考试成绩
     * @param page 页码
     * @param size 每页大小
     * @param examId 考试ID
     * @param published 发布状态
     * @return 分页成绩列表
     */
    @GetMapping("/my")
    @PreAuthorize("hasAuthority('exam:take')")
    public ResponseEntity<PageResponse<ExamResultDto>> getMyResults(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long examId,
            @RequestParam(required = false) Boolean published) {
        log.info("获取用户考试成绩 - 页码: {}, 大小: {}, 考试ID: {}, 发布状态: {}", page, size, examId, published);
        
        Long userId = SecurityUtils.getCurrentUserId();
        PageResponse<ExamResultDto> results = examResultService.getMyResults(userId, page, size, examId, published);
        return ResponseEntity.ok(results);
    }
    
    /**
     * 获取考试成绩统计信息
     * @param examId 考试ID
     * @return 统计信息
     */
    @GetMapping("/statistics/{examId}")
    @PreAuthorize("hasAuthority('exam_result:view')")
    public ResponseEntity<Map<String, Object>> getResultStatistics(@PathVariable Long examId) {
        log.info("获取考试成绩统计信息 - 考试ID: {}", examId);
        Map<String, Object> statistics = examResultService.getResultStatistics(examId);
        return ResponseEntity.ok(statistics);
    }
    
    /**
     * 获取考试排名
     * @param examId 考试ID
     * @return 排名列表
     */
    @GetMapping("/ranking/{examId}")
    @PreAuthorize("hasAuthority('exam_result:view')")
    public ResponseEntity<List<ExamResultDto>> getExamRanking(@PathVariable Long examId) {
        log.info("获取考试排名 - 考试ID: {}", examId);
        List<ExamResultDto> ranking = examResultService.getExamRanking(examId);
        return ResponseEntity.ok(ranking);
    }
}